package logic

import (
	"blog/blogrpc/models/cache"
	"blog/blogrpc/models/mysql"
	"context"
	"fmt"

	"blog/blogrpc/blogrpc"
	"blog/blogrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *blogrpc.UserLoginRequest) (*blogrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "captcha"+in.Username).Val()
	if get != in.CaptCode {
		return nil, fmt.Errorf("图形验证码错误,请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户未注册,禁止登录")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}
	return &blogrpc.UserLoginResponse{
		Userid: int64(user.ID),
	}, nil
}
